package design.patterns.builder.framework;

import java.io.*;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2020-06-08 23:03
 */

public class CloneUtil2<T> {
    public static <T> T cloneTo(T t){
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objOutStream = null;
        ObjectInputStream objInStream = null;
        T ans = null;
        try {
            objOutStream = new ObjectOutputStream(outputStream);
            objOutStream.writeObject(t);
            objOutStream.flush();
            objInStream = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
            ans = (T) objInStream.readObject();
        } catch (IOException e) {
            throw new RuntimeException();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(objOutStream != null){
                try {
                    objOutStream.close();
                    objOutStream = null;
                } catch (IOException e) {
                    throw new RuntimeException();
                }
            }
            if(objInStream == null){
                try {
                    objInStream.close();
                    objInStream = null;
                } catch (IOException e) {
                    throw new RuntimeException();
                }
            }
        }
        return ans;
    }
}
